<?php

namespace App\Tools\Base;

use App\Http\Controllers\Api\BaseController;
use App\Models\Api\User;
use App\Tools\AliOss;
use App\Tools\Upload;
use App\Http\Tools\File;
use Illuminate\Http\Request;

class Avatar extends BaseController
{
    private $img_max_size;

    /**
     * @name index
     * @description  文件上传
     * @param
     * type：上传文件类型（avatar：头像；alipay：支付宝二维码；weixin：微信二维码）
     * file：文件对象
     * @return
     * 成功：返回file_url文件地址
     * 失败：返回错误码及提示
     */
    public function upload($dir)
    {
        $upload_file = Request()->file('file');
        //\Log::info($upload_file);
       // var_dump($upload_file);die;

        if (isset($upload_file)) {
            //验证最大上传大小限制
            $maxSize = config('app.file_maxsize') * 1024 * 1024;
            // if ($upload_file->getSize() >= $maxSize) {
            //     //var_dump($upload_file->getClientOriginalName());die;
            //     return response()->json(['code'=>10034,'msg'=>'文件超出大小']);
            // }
           $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif','mp4']; // Add your allowed extensions here

            $fileExtension = $upload_file->getClientOriginalExtension();
           if (in_array(strtolower($fileExtension), $allowedExtensions)) {
            $filePath = "upload/" . date('Y-m-d') . "/";
            $filename = md5($upload_file->getClientOriginalName() . time() . rand()) . "." . $upload_file->getClientOriginalExtension();

            $content = file_get_contents($upload_file->getPath() . "/" . $upload_file->getFilename());

            try {
                (AliOss::getInstance())->ossUpload($filePath . $filename, $content);
            } catch (OssException $e) {
                $result = [
                    'code' => 10034,
                    'msg'  => $e->getMessage(),
                ];
            }
            // 如果文件是mp4格式，添加视频地址
        // if (strtolower($fileExtension) === 'mp4') {
        //     $result['data']['video_url'] = '/' .$filePath.$filename.'?x-oss-process=video/snapshot,t_1000,m_fast,ar_auto'; // 修改为你的视频地址
        // }else{
        //   $result['data']['img_url'] = '/' . $filePath.$filename.'?x-oss-process=image/resize,w_100/auto-orient,1'; // 修改为你的视频地址
        // }
            $result = [
                    'code' => 200,
                    'data' => [
                        'filename'    => $upload_file->getClientOriginalName(),
                        'url' => '/'.$filePath.$filename,
                    ],
                    'msg'  => 'ok',
                ];
            return response()->json($result);
           }else{
            return response()->json(['code'=>10034,'msg'=>'文件格式不对呀小朋友(^ ^)']);
           }
        } else {
            return response()->json(['code' => 10033, 'msg' => '文件不存在']);
        }
    }

    /**
     * 批量上传图片
     * @return [type] [description]
     */
    public function uploads($path = 'uploads')
    {
        if (empty($_FILES)) {
            return response()->json(['code' => 10033, 'msg' => 'File is not exited.']);
        }

        $files = [];
        foreach ($_FILES as $k => $f) {
            $temp   = Request()->file($k);
            $config = ['size' => $this->img_max_size, 'ext' => 'jpg,png,gif'];
            //            $path = 'picture'.DS.$dir;
            // tp5 文件上传验证
            $info = $temp->validate($config)->oss($path);
            // 获取文件名
            $filename = $info->get_filename();

            if (!$info) {
                $result = [
                    'code' => 10034,
                    'msg'  => $temp->getError(),
                ];
            }
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());
            try {
                $this->ossClient->putObject($this->bucket, $filename, $content);
            } catch (OssException $e) {
                $result = [
                    'code' => 10034,
                    'msg'  => $e->getMessage(),
                ];
            }
            if (isset($result['code']) && $result['code'] != 200) {
                return response()->json($result);
            }

            //            $filename = str_replace('upload','uploads',$filename);

            $files[] = DS . $filename;
        }
        return response()->json(['code' => 10034, 'data' => $files, 'msg' => 'Success']);
    }

    /**
     * 批量上传图片
     * @return [type] [description]
     */
    public function uploads_array($path = 'uploads')
    {
        if (empty($_FILES)) {
            return ['imgs' => [], 'error' => []];
        }

        $files = [];
        foreach ($_FILES as $k => $f) {
            $temp   = Request()->file($k);
            $config = ['size' => $this->img_max_size, 'ext' => 'jpg,png,gif'];
            //            $path = 'picture'.DS.$dir;
            // tp5 文件上传验证
            $info = $temp->validate($config)->oss($path);
            // 获取文件名
            $filename = $info->get_filename();

            if (!$info) {
                $files['error'][] = $temp->getError();
            }
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());
            try {
                $this->ossClient->putObject($this->bucket, $filename, $content);
            } catch (OssException $e) {
                $result = [
                    'code' => 10034,
                    'msg'  => $e->getMessage(),
                ];
            }
            if (isset($result['code']) && $result['code'] != 200) {
                return response()->json($result);
            }

            //            $filename = str_replace('upload','uploads',$filename);

            $files['imgs'][] = DS . $filename;
        }
        return $files;
    }

    //上传图片
    public function postImageUpload($param)
    {
        $file               = request()->file('avatar');
        $allowed_extensions = ['png', 'jpg', 'jpeg', 'gif'];
        $clientOriginalExt  = $file->getClientOriginalExtension();
        if ($clientOriginalExt && !in_array($clientOriginalExt, $allowed_extensions)) {
            return response()->json(['code' => 403, '', 'msg' => 'fail']);
        }
        $map  = ['id' => $request->uid];
        $info = (new User())->getUserinfo($map);

        $fileName  = md5(time()) . '.' . $clientOriginalExt;
        $saveDir   = 'upload/' . date('Y') . '/' . $info['id'] . '/';
        $fileMoved = $file->move(public_path($saveDir), $fileName);
        if (!empty($info['avatar']) && is_file(public_path($info['avatar']))) {
            $file = public_path($info['avatar']);
            @unlink($file);
        }
        if ($fileMoved) {
            $result = [
                'code' => 200,
                'data' => [
                    'path'     => $saveDir,
                    'filename' => $fileName,
                ],
                'msg'  => 'ok',
            ];
        } else {
            $result = [
                'code' => 10034,
                'msg'  => '失败',
            ];
        }
        return response()->json($result);
    }
    /**
     * 获取一个OssClient实例
     * @return null|OssClient
     */
    protected static function getInstance()
    {
        if (!(self::$_instance instanceof OssClient)) {
            try {
                self::$_instance = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
            } catch (OssException $e) {
                printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
                printf($e->getMessage() . "\n");
                return null;
            }
        }
        return self::$_instance;
    }
    /**
     * 获取bucket
     * @return string
     */
    protected static function getBucketName()
    {
        return self::bucket;
    }
}
